package com.ckm.aop;

import com.ckm.annotation.TeacherRole;
import com.ckm.entity.Teacher;
import com.ckm.exception.BusinessException;
import jakarta.servlet.http.HttpServletRequest;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;

@Aspect
@Component
public class TeacherRoleAspect {

    @Autowired
    private RedisTemplate<Object,Object> redisTemplate;

    @Before("@annotation(com.ckm.annotation.TeacherRole)")
    public void before(JoinPoint joinPoint) {
        HttpServletRequest request = (HttpServletRequest) RequestContextHolder.getRequestAttributes();
        assert request != null;
        String token = request.getHeader("token");
        if(token==null || token.isEmpty()){
            throw new BusinessException(250,"未登录");
        }
        if (Boolean.FALSE.equals(redisTemplate.hasKey(token))){
            throw new BusinessException(250,"未登录");
        }
        Teacher teacher = (Teacher) redisTemplate.opsForValue().get(token);
        TeacherRole teacherRole =
                ((MethodSignature) joinPoint.getSignature())
                        .getMethod().getAnnotation(TeacherRole.class);
        assert teacher != null;
        if (teacher.getRole()> teacherRole.value()){
            throw new BusinessException(250,"无权限访问");
        }
    }
}
